/**
 * 埋点测试控制台页面
 * @author lhx
 * 功能：全面测试埋点组件的各项功能，包括数据收集、存储、上传等
 */

import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  RefreshControl,
  Dimensions,
  Switch,
  TextInput,
  FlatList,
  Modal,
  ActivityIndicator,
  Platform
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';

// 导入埋点相关组件和工具
import ClickTrackerLhx, { 
  TrackedTouchableOpacityLhx,
  TrackedViewLhx 
} from '../utils/components/ClickTrackerLhx';
import { 
  EventPriority,
  TrackingEvent,
  ClickEventProperties 
} from '../utils/types/trackingTypes';
import {
  selectTrackingState,
  selectTrackingEvents,
  selectTrackingConfig,
  selectCurrentSession,
  selectUnuploadedEvents,
  selectIsUploading,
  updateConfig,
  clearAllData
} from '../store/slices/trackingSliceLhx';
import TrackingManagerLhx from '../utils/managers/TrackingManagerLhx';
import TrackingStorageLhx from '../utils/storage/trackingStorageLhx';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

// 模拟车辆数据
const MOCK_CARS = [
  { id: 'car_001', brand: 'BMW', model: 'X5', price: 150000, year: 2020 },
  { id: 'car_002', brand: '奔驰', model: 'C级', price: 120000, year: 2019 },
  { id: 'car_003', brand: '奥迪', model: 'A4', price: 180000, year: 2021 },
  { id: 'car_004', brand: '大众', model: '帕萨特', price: 90000, year: 2020 },
  { id: 'car_005', brand: '丰田', model: '凯美瑞', price: 110000, year: 2021 },
];

// 筛选选项
const FILTER_OPTIONS = [
  { id: 'price', label: '价格筛选', icon: '💰' },
  { id: 'brand', label: '品牌筛选', icon: '🏷️' },
  { id: 'year', label: '年份筛选', icon: '📅' },
  { id: 'mileage', label: '里程筛选', icon: '🛣️' },
];

// 交互操作选项
const INTERACTION_OPTIONS = [
  { id: 'favorite', label: '收藏', icon: '❤️' },
  { id: 'share', label: '分享', icon: '📤' },
  { id: 'compare', label: '对比', icon: '📊' },
  { id: 'contact', label: '联系', icon: '📞' },
  { id: 'test_drive', label: '试驾', icon: '🚗' },
  { id: 'inquiry', label: '询价', icon: '💬' },
];

const TrackingTestHomeLhx: React.FC = () => {
  const dispatch = useDispatch();
  const trackingState = useSelector(selectTrackingState);
  const trackingEvents = useSelector(selectTrackingEvents);
  const trackingConfig = useSelector(selectTrackingConfig);
  const currentSession = useSelector(selectCurrentSession);
  const unuploadedEvents = useSelector(selectUnuploadedEvents);
  const isUploading = useSelector(selectIsUploading);

  // 组件状态
  const [refreshing, setRefreshing] = useState(false);
  const [statistics, setStatistics] = useState({
    memoryEvents: 0,
    storageEvents: 0,
    unuploadedEvents: 0,
    storageSize: 0,
    lastUploadTime: 0
  });
  const [clickCounts, setClickCounts] = useState<{[key: string]: number}>({});
  const [filterCounts, setFilterCounts] = useState<{[key: string]: number}>({});
  const [interactionCounts, setInteractionCounts] = useState<{[key: string]: number}>({});
  const [showEventDetail, setShowEventDetail] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState<TrackingEvent | null>(null);
  const [eventFilter, setEventFilter] = useState('all');
  const [isStressTesting, setIsStressTesting] = useState(false);
  const [stressTestCount, setStressTestCount] = useState(0);
  const [performanceMetrics, setPerformanceMetrics] = useState({
    avgResponseTime: 0,
    memoryUsage: 0,
    successRate: 0
  });

  // 引用
  const stressTestTimer = useRef<NodeJS.Timeout | null>(null);
  const performanceTimer = useRef<NodeJS.Timeout | null>(null);

  // 获取管理器实例
  const trackingManager = TrackingManagerLhx.getInstance();

  // 初始化
  useEffect(() => {
    initializeTracking();
    startPerformanceMonitoring();
    
    return () => {
      if (stressTestTimer.current) {
        clearInterval(stressTestTimer.current);
      }
      if (performanceTimer.current) {
        clearInterval(performanceTimer.current);
      }
    };
  }, []);

  // 监听埋点事件变化，更新统计信息
  useEffect(() => {
    updateStatistics();
  }, [trackingEvents, unuploadedEvents]);

  // 初始化埋点系统
  const initializeTracking = async () => {
    try {
      await trackingManager.initialize('test_user_lhx');
      console.log('✅ 埋点系统初始化成功');
    } catch (error) {
      console.error('❌ 埋点系统初始化失败:', error);
      Alert.alert('初始化失败', '埋点系统初始化失败，请检查配置');
    }
  };

  // 更新统计信息
  const updateStatistics = async () => {
    try {
      const stats = await trackingManager.getStatistics();
      setStatistics(stats);
      
      // 计算成功率
      const totalEvents = stats.memoryEvents + stats.storageEvents;
      const failedEvents = unuploadedEvents.filter(e => e.retryCount > 0).length;
      const successRate = totalEvents > 0 ? ((totalEvents - failedEvents) / totalEvents) * 100 : 100;
      
      setPerformanceMetrics(prev => ({
        ...prev,
        successRate: Math.round(successRate * 100) / 100
      }));
    } catch (error) {
      console.error('更新统计信息失败:', error);
    }
  };

  // 开始性能监控
  const startPerformanceMonitoring = () => {
    performanceTimer.current = setInterval(() => {
      // 模拟性能指标计算
      const avgResponseTime = Math.round(Math.random() * 20 + 10); // 10-30ms
      const memoryUsage = Math.round(trackingEvents.length * 0.1 + Math.random() * 2); // MB
      
      setPerformanceMetrics(prev => ({
        ...prev,
        avgResponseTime,
        memoryUsage
      }));
    }, 2000);
  };

  // 刷新页面数据
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await updateStatistics();
    setRefreshing(false);
  }, []);

  // 处理车辆卡片点击
  const handleCarClick = useCallback((car: typeof MOCK_CARS[0], index: number) => {
    setClickCounts(prev => ({
      ...prev,
      [car.id]: (prev[car.id] || 0) + 1
    }));
    
    console.log(`🚗 车辆点击: ${car.brand} ${car.model}`);
  }, []);

  // 处理筛选器点击
  const handleFilterClick = useCallback((filter: typeof FILTER_OPTIONS[0]) => {
    setFilterCounts(prev => ({
      ...prev,
      [filter.id]: (prev[filter.id] || 0) + 1
    }));
    
    console.log(`🔍 筛选器使用: ${filter.label}`);
  }, []);

  // 处理交互操作点击
  const handleInteractionClick = useCallback((interaction: typeof INTERACTION_OPTIONS[0], carId?: string) => {
    setInteractionCounts(prev => ({
      ...prev,
      [interaction.id]: (prev[interaction.id] || 0) + 1
    }));
    
    console.log(`❤️ 交互操作: ${interaction.label}`);
  }, []);

  // 立即上传
  const handleUploadNow = async () => {
    try {
      const success = await trackingManager.uploadEvents();
      Alert.alert(
        success ? '上传成功' : '上传失败',
        success ? '所有事件已成功上传' : '部分事件上传失败，请稍后重试'
      );
    } catch (error) {
      Alert.alert('上传异常', '上传过程中发生异常');
    }
  };

  // 清空所有数据
  const handleClearData = () => {
    Alert.alert(
      '确认清空',
      '这将清空所有埋点数据，是否继续？',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确认',
          style: 'destructive',
          onPress: async () => {
            try {
              await trackingManager.reset();
              dispatch(clearAllData());
              setClickCounts({});
              setFilterCounts({});
              setInteractionCounts({});
              Alert.alert('清空成功', '所有数据已清空');
            } catch (error) {
              Alert.alert('清空失败', '清空数据时发生错误');
            }
          }
        }
      ]
    );
  };

  // 模拟网络失败
  const handleSimulateFailure = () => {
    Alert.alert('模拟网络异常', '下次上传将模拟失败，用于测试重试机制');
    // 这里可以设置一个标志来模拟失败
  };

  // 切换埋点启用状态
  const handleToggleTracking = (enabled: boolean) => {
    dispatch(updateConfig({ enabled }));
    Alert.alert(
      enabled ? '埋点已启用' : '埋点已禁用',
      enabled ? '现在开始记录用户行为' : '停止记录用户行为'
    );
  };

  // 开始压力测试
  const startStressTest = () => {
    setIsStressTesting(true);
    setStressTestCount(0);
    
    stressTestTimer.current = setInterval(() => {
      setStressTestCount(prev => {
        const newCount = prev + 1;
        
        // 模拟快速点击事件
        const randomCar = MOCK_CARS[Math.floor(Math.random() * MOCK_CARS.length)];
        handleCarClick(randomCar, Math.floor(Math.random() * MOCK_CARS.length));
        
        // 测试100次后停止
        if (newCount >= 100) {
          if (stressTestTimer.current) {
            clearInterval(stressTestTimer.current);
          }
          setIsStressTesting(false);
          Alert.alert('压力测试完成', `已完成${newCount}次模拟点击测试`);
        }
        
        return newCount;
      });
    }, 50); // 每50ms一次点击
  };

  // 停止压力测试
  const stopStressTest = () => {
    if (stressTestTimer.current) {
      clearInterval(stressTestTimer.current);
    }
    setIsStressTesting(false);
    Alert.alert('压力测试已停止', `共完成${stressTestCount}次测试`);
  };

  // 导出数据
  const handleExportData = async () => {
    try {
      const exportData = {
        statistics,
        events: trackingEvents,
        clickCounts,
        filterCounts,
        interactionCounts,
        performanceMetrics,
        session: currentSession,
        config: trackingConfig,
        timestamp: new Date().toISOString()
      };
      
      console.log('📊 导出数据:', JSON.stringify(exportData, null, 2));
      Alert.alert(
        '数据导出成功',
        '数据已输出到控制台，实际项目中可以保存到文件或发送到服务器'
      );
    } catch (error) {
      Alert.alert('导出失败', '数据导出时发生错误');
    }
  };

  // 查看事件详情
  const handleViewEventDetail = (event: TrackingEvent) => {
    setSelectedEvent(event);
    setShowEventDetail(true);
  };

  // 过滤事件列表
  const getFilteredEvents = () => {
    let filtered = [...trackingEvents];
    
    if (eventFilter !== 'all') {
      filtered = filtered.filter(event => event.eventType === eventFilter);
    }
    
    return filtered.slice(0, 20); // 只显示最近20条
  };

  // 渲染统计面板
  const renderStatisticsPanel = () => (
    <View style={styles.panel}>
      <Text style={styles.panelTitle}>📊 实时统计面板</Text>
      <View style={styles.statsGrid}>
        <View style={styles.statItem}>
          <Text style={styles.statValue}>{statistics.memoryEvents}</Text>
          <Text style={styles.statLabel}>内存事件</Text>
        </View>
        <View style={styles.statItem}>
          <Text style={styles.statValue}>{statistics.storageEvents}</Text>
          <Text style={styles.statLabel}>本地存储</Text>
        </View>
        <View style={styles.statItem}>
          <Text style={styles.statValue}>{statistics.unuploadedEvents}</Text>
          <Text style={styles.statLabel}>未上传</Text>
        </View>
        <View style={styles.statItem}>
          <Text style={styles.statValue}>{(statistics.storageSize / 1024).toFixed(1)}KB</Text>
          <Text style={styles.statLabel}>存储大小</Text>
        </View>
        <View style={styles.statItem}>
          <Text style={styles.statValue}>{performanceMetrics.successRate}%</Text>
          <Text style={styles.statLabel}>成功率</Text>
        </View>
        <View style={styles.statItem}>
          <Text style={styles.statValue}>
            {statistics.lastUploadTime ? '刚刚' : '未上传'}
          </Text>
          <Text style={styles.statLabel}>最后上传</Text>
        </View>
      </View>
    </View>
  );

  // 渲染控制面板
  const renderControlPanel = () => (
    <View style={styles.panel}>
      <Text style={styles.panelTitle}>🎛️ 控制操作区</Text>
      <View style={styles.controlGrid}>
        <TouchableOpacity style={styles.controlButton} onPress={onRefresh}>
          <Text style={styles.controlButtonText}>🔄 刷新统计</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.controlButton} onPress={handleClearData}>
          <Text style={styles.controlButtonText}>🗑️ 清空数据</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          style={[styles.controlButton, isUploading && styles.controlButtonDisabled]} 
          onPress={handleUploadNow}
          disabled={isUploading}
        >
          <Text style={styles.controlButtonText}>
            {isUploading ? '📤 上传中...' : '📤 立即上传'}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.controlButton} onPress={handleSimulateFailure}>
          <Text style={styles.controlButtonText}>❌ 模拟失败</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          style={[styles.controlButton, isStressTesting && styles.controlButtonActive]} 
          onPress={isStressTesting ? stopStressTest : startStressTest}
        >
          <Text style={styles.controlButtonText}>
            {isStressTesting ? `⏹️ 停止测试(${stressTestCount})` : '🔥 压力测试'}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.controlButton} onPress={handleExportData}>
          <Text style={styles.controlButtonText}>📋 导出数据</Text>
        </TouchableOpacity>
      </View>
      
      <View style={styles.switchContainer}>
        <Text style={styles.switchLabel}>埋点启用状态:</Text>
        <Switch
          value={trackingConfig.enabled}
          onValueChange={handleToggleTracking}
          trackColor={{ false: '#767577', true: '#4CAF50' }}
          thumbColor={trackingConfig.enabled ? '#ffffff' : '#f4f3f4'}
        />
      </View>
    </View>
  );

  // 渲染车辆测试区
  const renderCarTestArea = () => (
    <View style={styles.panel}>
      <Text style={styles.panelTitle}>🚗 推荐车辆测试区</Text>
      <ScrollView horizontal showsHorizontalScrollIndicator={false}>
        {MOCK_CARS.map((car, index) => (
          <ClickTrackerLhx
            key={car.id}
            eventName="recommendation_car_click"
            properties={{
              carId: car.id,
              position: index,
              price: car.price,
              brand: car.brand,
              model: car.model,
              algorithm: 'test_algorithm'
            }}
            priority={EventPriority.HIGH}
            onPress={() => handleCarClick(car, index)}
            onTrack={(event) => console.log('🎯 埋点事件:', event.eventName)}
          >
            <View style={styles.carCard}>
              <Text style={styles.carBrand}>{car.brand}</Text>
              <Text style={styles.carModel}>{car.model}</Text>
              <Text style={styles.carPrice}>¥{(car.price / 10000).toFixed(1)}万</Text>
              <Text style={styles.carYear}>{car.year}年</Text>
              <View style={styles.clickCounter}>
                <Text style={styles.clickCountText}>
                  点击: {clickCounts[car.id] || 0}次
                </Text>
              </View>
            </View>
          </ClickTrackerLhx>
        ))}
      </ScrollView>
    </View>
  );

  // 渲染筛选测试区
  const renderFilterTestArea = () => (
    <View style={styles.panel}>
      <Text style={styles.panelTitle}>🔍 搜索筛选测试区</Text>
      <View style={styles.filterGrid}>
        {FILTER_OPTIONS.map((filter) => (
          <ClickTrackerLhx
            key={filter.id}
            eventName="filter_button_click"
            properties={{
              filterType: filter.id,
              filterLabel: filter.label
            }}
            priority={EventPriority.MEDIUM}
            onPress={() => handleFilterClick(filter)}
          >
            <View style={styles.filterButton}>
              <Text style={styles.filterIcon}>{filter.icon}</Text>
              <Text style={styles.filterLabel}>{filter.label}</Text>
              <Text style={styles.filterCount}>
                使用: {filterCounts[filter.id] || 0}次
              </Text>
            </View>
          </ClickTrackerLhx>
        ))}
      </View>
    </View>
  );

  // 渲染交互测试区
  const renderInteractionTestArea = () => (
    <View style={styles.panel}>
      <Text style={styles.panelTitle}>❤️ 交互操作测试区</Text>
      <View style={styles.interactionGrid}>
        {INTERACTION_OPTIONS.map((interaction) => (
          <ClickTrackerLhx
            key={interaction.id}
            eventName={`${interaction.id}_click`}
            properties={{
              interactionType: interaction.id,
              interactionLabel: interaction.label,
              carId: 'test_car_123'
            }}
            priority={EventPriority.MEDIUM}
            onPress={() => handleInteractionClick(interaction)}
          >
            <View style={styles.interactionButton}>
              <Text style={styles.interactionIcon}>{interaction.icon}</Text>
              <Text style={styles.interactionLabel}>{interaction.label}</Text>
              <Text style={styles.interactionCount}>
                {interactionCounts[interaction.id] || 0}
              </Text>
            </View>
          </ClickTrackerLhx>
        ))}
      </View>
    </View>
  );

  // 注意：renderEventLog 函数已被重构到主 FlatList 中，不再需要单独的函数

  // 渲染性能监控
  const renderPerformanceMonitor = () => (
    <View style={styles.panel}>
      <Text style={styles.panelTitle}>⚡ 性能监控</Text>
      <View style={styles.performanceGrid}>
        <View style={styles.performanceItem}>
          <Text style={styles.performanceValue}>{performanceMetrics.avgResponseTime}ms</Text>
          <Text style={styles.performanceLabel}>平均响应时间</Text>
        </View>
        <View style={styles.performanceItem}>
          <Text style={styles.performanceValue}>{performanceMetrics.memoryUsage}MB</Text>
          <Text style={styles.performanceLabel}>内存使用</Text>
        </View>
        <View style={styles.performanceItem}>
          <Text style={styles.performanceValue}>{performanceMetrics.successRate}%</Text>
          <Text style={styles.performanceLabel}>成功率</Text>
        </View>
      </View>
      
      {/* 会话信息 */}
      <View style={styles.sessionInfo}>
        <Text style={styles.sessionTitle}>当前会话信息:</Text>
        <Text style={styles.sessionText}>会话ID: {currentSession.sessionId}</Text>
        <Text style={styles.sessionText}>用户ID: {currentSession.userId || '未设置'}</Text>
        <Text style={styles.sessionText}>
          会话时长: {Math.floor((Date.now() - currentSession.startTime) / 1000)}秒
        </Text>
      </View>
    </View>
  );

  // 渲染事件详情模态框
  const renderEventDetailModal = () => (
    <Modal
      visible={showEventDetail}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={() => setShowEventDetail(false)}
    >
      <View style={styles.modalContainer}>
        <View style={styles.modalHeader}>
          <Text style={styles.modalTitle}>事件详情</Text>
          <TouchableOpacity
            style={styles.modalCloseButton}
            onPress={() => setShowEventDetail(false)}
          >
            <Text style={styles.modalCloseText}>关闭</Text>
          </TouchableOpacity>
        </View>
        
        {selectedEvent && (
          <ScrollView style={styles.modalContent}>
            <View style={styles.detailSection}>
              <Text style={styles.detailSectionTitle}>基本信息</Text>
              <Text style={styles.detailText}>ID: {selectedEvent.id}</Text>
              <Text style={styles.detailText}>事件名称: {selectedEvent.eventName}</Text>
              <Text style={styles.detailText}>事件类型: {selectedEvent.eventType}</Text>
              <Text style={styles.detailText}>优先级: {selectedEvent.priority}</Text>
              <Text style={styles.detailText}>
                时间戳: {new Date(selectedEvent.timestamp).toLocaleString()}
              </Text>
              <Text style={styles.detailText}>
                状态: {selectedEvent.uploaded ? '已上传' : '待上传'}
              </Text>
              <Text style={styles.detailText}>重试次数: {selectedEvent.retryCount}</Text>
            </View>
            
            <View style={styles.detailSection}>
              <Text style={styles.detailSectionTitle}>事件属性</Text>
              <Text style={styles.detailCode}>
                {JSON.stringify(selectedEvent.properties, null, 2)}
              </Text>
            </View>
            
            <View style={styles.detailSection}>
              <Text style={styles.detailSectionTitle}>上下文信息</Text>
              <Text style={styles.detailCode}>
                {JSON.stringify(selectedEvent.context, null, 2)}
              </Text>
            </View>
          </ScrollView>
        )}
      </View>
    </Modal>
  );

  // 渲染页面头部内容
  const renderHeaderContent = () => (
    <View>
      {/* 页面标题 */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>🧪 埋点测试控制台 (lhx)</Text>
        <Text style={styles.headerSubtitle}>
          智能推荐模块埋点功能全面测试平台
        </Text>
      </View>

      {/* 统计面板 */}
      {renderStatisticsPanel()}

      {/* 控制面板 */}
      {renderControlPanel()}

      {/* 车辆测试区 */}
      {renderCarTestArea()}

      {/* 筛选测试区 */}
      {renderFilterTestArea()}

      {/* 交互测试区 */}
      {renderInteractionTestArea()}

      {/* 事件日志标题和筛选器 */}
      <View style={styles.panel}>
        <Text style={styles.panelTitle}>📋 事件实时日志</Text>
        
        {/* 筛选器 */}
        <View style={styles.filterRow}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            {['all', 'click', 'view', 'scroll'].map((type) => (
              <TouchableOpacity
                key={type}
                style={[
                  styles.filterChip,
                  eventFilter === type && styles.filterChipActive
                ]}
                onPress={() => setEventFilter(type)}
              >
                <Text style={[
                  styles.filterChipText,
                  eventFilter === type && styles.filterChipTextActive
                ]}>
                  {type === 'all' ? '全部' : type}
                </Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>
      </View>
    </View>
  );

  // 渲染页面底部内容
  const renderFooterContent = () => (
    <View>
      {/* 性能监控 */}
      {renderPerformanceMonitor()}
      
      {/* 底部间距 */}
      <View style={styles.bottomSpacer} />
    </View>
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={getFilteredEvents()}
        keyExtractor={(item) => item.id}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListHeaderComponent={renderHeaderContent}
        ListFooterComponent={renderFooterContent}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={styles.eventItem}
            onPress={() => handleViewEventDetail(item)}
          >
            <View style={styles.eventHeader}>
              <Text style={styles.eventStatus}>
                {item.uploaded ? '✅' : item.retryCount > 0 ? '❌' : '⏳'}
              </Text>
              <Text style={styles.eventTime}>
                {new Date(item.timestamp).toLocaleTimeString()}
              </Text>
              <Text style={styles.eventName}>{item.eventName}</Text>
            </View>
            <Text style={styles.eventProperties} numberOfLines={1}>
              {JSON.stringify(item.properties)}
            </Text>
          </TouchableOpacity>
        )}
        ListEmptyComponent={
          <Text style={styles.emptyText}>暂无事件数据</Text>
        }
        style={styles.eventList}
      />
      
      {/* 事件详情模态框 */}
      {renderEventDetailModal()}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    backgroundColor: '#2196F3',
    padding: 20,
    paddingTop: Platform.OS === 'ios' ? 50 : 20,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: 'white',
    textAlign: 'center',
  },
  headerSubtitle: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.8)',
    textAlign: 'center',
    marginTop: 4,
  },
  panel: {
    backgroundColor: 'white',
    margin: 10,
    borderRadius: 8,
    padding: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  panelTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 15,
    color: '#333',
  },
  statsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  statItem: {
    width: '48%',
    alignItems: 'center',
    marginBottom: 15,
    padding: 10,
    backgroundColor: '#f8f9fa',
    borderRadius: 6,
  },
  statValue: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#2196F3',
  },
  statLabel: {
    fontSize: 12,
    color: '#666',
    marginTop: 4,
  },
  controlGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  controlButton: {
    width: '48%',
    backgroundColor: '#4CAF50',
    padding: 12,
    borderRadius: 6,
    marginBottom: 10,
    alignItems: 'center',
  },
  controlButtonText: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 12,
  },
  controlButtonDisabled: {
    backgroundColor: '#ccc',
  },
  controlButtonActive: {
    backgroundColor: '#FF5722',
  },
  switchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 15,
    paddingTop: 15,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  switchLabel: {
    fontSize: 14,
    color: '#333',
  },
  carCard: {
    width: 120,
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    marginRight: 10,
    borderWidth: 1,
    borderColor: '#ddd',
    alignItems: 'center',
  },
  carBrand: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333',
  },
  carModel: {
    fontSize: 12,
    color: '#666',
    marginTop: 2,
  },
  carPrice: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#e74c3c',
    marginTop: 4,
  },
  carYear: {
    fontSize: 10,
    color: '#999',
    marginTop: 2,
  },
  clickCounter: {
    marginTop: 8,
    backgroundColor: '#e3f2fd',
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 10,
  },
  clickCountText: {
    fontSize: 10,
    color: '#1976d2',
  },
  filterGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  filterButton: {
    width: '48%',
    backgroundColor: '#f8f9fa',
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#e9ecef',
  },
  filterIcon: {
    fontSize: 20,
    marginBottom: 5,
  },
  filterLabel: {
    fontSize: 12,
    fontWeight: 'bold',
    color: '#333',
  },
  filterCount: {
    fontSize: 10,
    color: '#666',
    marginTop: 4,
  },
  interactionGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  interactionButton: {
    width: '30%',
    backgroundColor: '#fff3e0',
    padding: 12,
    borderRadius: 8,
    alignItems: 'center',
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#ffcc02',
  },
  interactionIcon: {
    fontSize: 16,
    marginBottom: 4,
  },
  interactionLabel: {
    fontSize: 10,
    fontWeight: 'bold',
    color: '#333',
  },
  interactionCount: {
    fontSize: 10,
    color: '#f57c00',
    marginTop: 2,
  },
  filterRow: {
    marginBottom: 10,
  },
  filterChip: {
    backgroundColor: '#f5f5f5',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
    marginRight: 8,
  },
  filterChipActive: {
    backgroundColor: '#2196F3',
  },
  filterChipText: {
    fontSize: 12,
    color: '#666',
  },
  filterChipTextActive: {
    color: 'white',
  },
  eventList: {
    flex: 1,
  },
  eventItem: {
    backgroundColor: '#f8f9fa',
    padding: 10,
    borderRadius: 6,
    marginBottom: 8,
  },
  eventHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  eventStatus: {
    fontSize: 12,
    marginRight: 8,
  },
  eventTime: {
    fontSize: 10,
    color: '#666',
    marginRight: 8,
  },
  eventName: {
    fontSize: 12,
    fontWeight: 'bold',
    color: '#333',
    flex: 1,
  },
  eventProperties: {
    fontSize: 10,
    color: '#999',
    marginTop: 4,
  },
  emptyText: {
    textAlign: 'center',
    color: '#999',
    fontStyle: 'italic',
    padding: 20,
  },
  performanceGrid: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 15,
  },
  performanceItem: {
    flex: 1,
    alignItems: 'center',
    padding: 10,
    backgroundColor: '#e8f5e8',
    marginHorizontal: 2,
    borderRadius: 6,
  },
  performanceValue: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#4CAF50',
  },
  performanceLabel: {
    fontSize: 10,
    color: '#666',
    marginTop: 4,
    textAlign: 'center',
  },
  sessionInfo: {
    backgroundColor: '#f0f0f0',
    padding: 10,
    borderRadius: 6,
  },
  sessionTitle: {
    fontSize: 12,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 5,
  },
  sessionText: {
    fontSize: 10,
    color: '#666',
    marginBottom: 2,
  },
  modalContainer: {
    flex: 1,
    backgroundColor: 'white',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    paddingTop: Platform.OS === 'ios' ? 50 : 20,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  modalCloseButton: {
    backgroundColor: '#2196F3',
    paddingHorizontal: 15,
    paddingVertical: 8,
    borderRadius: 6,
  },
  modalCloseText: {
    color: 'white',
    fontWeight: 'bold',
  },
  modalContent: {
    flex: 1,
    padding: 20,
  },
  detailSection: {
    marginBottom: 20,
  },
  detailSectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 10,
  },
  detailText: {
    fontSize: 14,
    color: '#666',
    marginBottom: 5,
  },
  detailCode: {
    backgroundColor: '#f5f5f5',
    padding: 10,
    borderRadius: 6,
    fontSize: 12,
    fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
    color: '#333',
  },
  bottomSpacer: {
    height: 50,
  },
});

export default TrackingTestHomeLhx;
